﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.IO;
using Microsoft.Win32.SafeHandles;
using UnityEngine;

//Excel加载器
public static class Utility
{
    ////获取一天的最大最小值成交价格
    //public static Vector2 GetMinMaxPriceOfKDay(KData[] datas)
    //{
    //    float min = float.MaxValue;
    //    float max = float.MinValue;

    //    foreach (var data in datas)
    //    {
    //        min = Math.Min(min, data.price);
    //        max = Math.Max(max, data.price);
    //    }
    //    return new Vector2(min,max);
    //}

    //////获取一天的最大最小成交额
    ////public static Vector2 GetMinMaxAmountOfKDay(List<KData> datas)
    ////{
    ////    float max = float.MinValue;

    ////    foreach (var data in datas) 
    ////    {
    ////        max = Math.Max(max, data.amount);
    ////    }
    ////    return new Vector2(0, max);
    ////}

    ////获取一天的最大最小成交量
    //public static Vector2 GetMinMaxVolOfKDay(List<KData> datas)
    //{
    //    float max = float.MinValue;

    //    foreach (var data in datas)
    //    {
    //        max = Math.Max(max, data.vol);
    //    }
    //    return new Vector2(0, max);
    //}

    ////获取一天总的成交额度
    //public static float GetTotalAMO(List<KData> datas)
    //{
    //    float total = 0;
    //    foreach (var data in datas)
    //    {
    //        total += data.price * data.vol;
    //    }
    //    return total;
    //}

    ////计算量效值
    //public static List<float> GetLiangXiaoList(List<KData> datas,ref float absMax)
    //{
    //    List<float> liangxiaoList = new List<float>();

    //    absMax = 0;
    //    for (int i = 0; i < datas.Count; i++)
    //    {
    //        float value = 0;
    //        if (i != 0)
    //        {
    //            //价格变化除以量
    //            value = (datas[i].price - datas[i - 1].price) / datas[i].vol;
    //            absMax = Mathf.Max(value, absMax);
    //        }
    //        liangxiaoList.Add(value);
    //    }
    //    return liangxiaoList;
    //}




    //路径类型枚举
    public enum UnityPathType
    {
        persistentDataPath,
        temporaryCachePath,
        streamingAssetsPath

    }
    //通过输入路径类型，返回相应路径
    public static string UnityDefaultPath(UnityPathType pathtype)
    {
        if (pathtype == UnityPathType.streamingAssetsPath) {
            return Application.streamingAssetsPath;
        }
        else if (pathtype == UnityPathType.persistentDataPath) {
            return PersistentDataPath;
        }
        else if (pathtype == UnityPathType.temporaryCachePath) {
            return CachePath;
        }
        return null;

    }

    //返回当前平台路径
    public static string GetDefaultPath(string strPath, UnityPathType pathtype)
    {
        return UnityDefaultPath(pathtype) + "/" + strPath;
    }



    private static string _persistentDataPath = null;//玩家PersistentDataPath路径

    //获取玩家PersistentDataPath路径
    public static string PersistentDataPath
    {
        get
        {

            if (_persistentDataPath == null) {
#if UNITY_EDITOR||UNITY_STANDALONE_WIN||UNITY_UNITY_STANDALONE_OSX || UNITY_STANDALONE_LINUX
                int idx = Application.dataPath.LastIndexOf('/');
                _persistentDataPath = Application.dataPath.Substring(0, idx) + "/Persistent";
#else
				_persistentDataPath = Application.persistentDataPath;
#endif
            }
            return _persistentDataPath;
        }
    }


    private static string _cachePath = null;
    //获取玩家TemporaryCachePath路径
    public static string CachePath
    {

        get
        {

            if (_cachePath == null) {
#if UNITY_EDITOR||UNITY_STANDALONE_WIN||UNITY_UNITY_STANDALONE_OSX
                int idx = Application.dataPath.LastIndexOf('/');
                _cachePath = Application.dataPath.Substring(0, idx) + "/Cache";

#else
				_cachePath = Application.temporaryCachePath;
#endif
            }
            return _cachePath;

        }
    }

    public static class EmptyArray<T>
    {
        public static readonly T[] Get = new T[0];
    }

    //读取全部行
    public static string[] SafeReadAllLine(string path, UnityPathType pathtype)
    {
        string ReadPath;//需要获取文件路径
        string DefaulPath = UnityDefaultPath(pathtype);//默认文件夹路径

        Debug.Log($"SafeReadAllLine {DefaulPath}");

        ////判断当前路径是否存在，不存在则创建
        //if (!Directory.Exists(DefaulPath))
        //{
        //    Directory.CreateDirectory(DefaulPath);
        //    //Debug.Log($"该文件路径不存在：{DefaulPath}");
        //    //return null;
        //}
        //streamingAssets在安卓平台上只能读，在ios和PC端可读可写
        //if (pathtype == UnityPathType.streamingAssetsPath) {
        //    Debug.Log("当前获取路径：" + DefaulPath);
        //    Debug.Log("streamingAssets路径不支持这类读取方式，请替换");
        //    return EmptyArray<string>.Get; ;
        //}
        ReadPath = DefaulPath + "/" + path;


        try {
            //Debug.Log("当前获取路径：" + ReadPath);
            if (!File.Exists(ReadPath)) {
                throw new ArgumentException();
            }
            Debug.Log("readLines success!!!");
            return File.ReadAllLines(ReadPath);

        }
        catch {
            Debug.Log(string.Format("当前文件不存在，请查看当前路径下是否存在该文件：{0}", ReadPath));
            return null;
        }
    }

    //读取文本（一个字符串）
    public static string SafeReadAllText(string path, UnityPathType pathtype)
    {
        string ReadPath;//需要获取文件路径
        string DefaulPath = UnityDefaultPath(pathtype);//默认文件夹路径
        //在streamingAssets路劲特殊处理
        if (pathtype == UnityPathType.streamingAssetsPath) {
            Debug.Log("当前获取路径：" + DefaulPath);

            //安卓平台的Streaming需要使用WWW进行加载读取
#if !UNITY_EDITOR && UNITY_ANDROID
           var www =new WWW(DefaulPath + "/" + path);
            while (!www.isDone) { }
            Debug.Log("readallText Success!!!");
            return www.text;
#elif !UNITY_EDITOR && UNITY_IOS
            Log.Print("readallText Success!!!");
            return SafeReadAllText(DefaulPath + "/" + path);
#else
            Debug.Log("readallText Success!!!");
            return SafeReadAllText(DefaulPath + "/" + path);
#endif
        }

        //判断当前路径是否存在，不存在则创建
        if (!Directory.Exists(DefaulPath)) {

            Debug.Log($"该文件路径不存在：{DefaulPath}");
            return null;
        }

        if (DefaulPath != null) {

            ReadPath = DefaulPath + "/" + path;


            try {
                //Debug.Log("当前获取路径：" + ReadPath);

                if (!File.Exists(ReadPath)) {
                    throw new ArgumentException();
                }



                Debug.Log("readallText Success!!!");
                return SafeReadAllText(ReadPath);

            }
            catch {
                Debug.Log(string.Format("当前文件不存在，请查看当前路径下是否存在该文件：{0}", ReadPath));
                return null;
            }
        }
        //Debug.LogError(string.Format("默认路径({0})设置失败", DefaulPath));
        return null;

    }


    //读取字节
    public static byte[] SafeReadAllByte(string path, UnityPathType pathtype)
    {
        string ReadPath;//需要获取文件路径
        string DefaulPath = UnityDefaultPath(pathtype);//默认文件夹路径
        //在streamingAssets路劲特殊处理
        if (pathtype == UnityPathType.streamingAssetsPath) {
            Debug.Log("当前获取路径：" + DefaulPath);

            //安卓平台的Streaming需要使用WWW进行加载读取

#if !UNITY_EDITOR && UNITY_ANDROID
        var www = new WWW(DefaulPath + "/" + path);
            while (!www.isDone) { }
            Debug.Log("readallBytes Success!!!");
            return www.bytes;
#elif !UNITY_EDITOR && UNITY_IOS
        Log.Print("readallBytes Success!!!");
        return SafeReadAllBytes(DefaulPath + "/" + path);
#else
            Debug.Log("readallBytes Success!!!");
            return SafeReadAllBytes(DefaulPath + "/" + path);
#endif

        }


        //判断当前路径是否存在，不存在则创建
        if (!Directory.Exists(DefaulPath)) {

            Debug.Log($"该文件路径不存在：{DefaulPath}");
            return null;
        }

        if (DefaulPath != null) {

            ReadPath = DefaulPath + "/" + path;


            try {
                //Debug.Log("当前获取路径：" + ReadPath);



                if (!File.Exists(ReadPath)) {
                    throw new ArgumentException();
                }




                Debug.Log("readallBytes Success!!!");
                return SafeReadAllBytes(ReadPath);

            }
            catch {
                Debug.Log(string.Format("当前文件不存在，请查看当前路径下是否存在该文件：{0}", ReadPath));
                return null;
            }
        }
        Debug.Log(string.Format("默认路径({0})设置失败", DefaulPath));
        return null;

    }


    public static string SafeReadAllText(string path)
    {
        if (!File.Exists(path)) {
            return null;
        }
        return File.ReadAllText(path);
    }
    //读取所有字节
    public static byte[] SafeReadAllBytes(string path)
    {
        if (!File.Exists(path)) {
            Debug.Log($"path:{path} 该路径下文件不存在");
            return null;
        }
        return File.ReadAllBytes(path);
    }


    /// <summary> 
    /// 将 Stream 转成 byte[] 
    /// </summary> 
    public static byte[] StreamToBytes(Stream stream)
    {
        byte[] bytes = new byte[stream.Length];
        stream.Read(bytes, 0, bytes.Length);

        // 设置当前流的位置为流的开始 
        stream.Seek(0, SeekOrigin.Begin);
        return bytes;
    }

    /// <summary> 
    /// 将 byte[] 转成 Stream 
    /// </summary> 
    public static Stream BytesToStream(byte[] bytes)
    {
        Stream stream = new MemoryStream(bytes);
        return stream;
    }


    /* - - - - - - - - - - - - - - - - - - - - - - - -  
     * Stream 和 文件之间的转换 
     * - - - - - - - - - - - - - - - - - - - - - - - */
    /// <summary> 
    /// 将 Stream 写入文件 
    /// </summary> 
    public static void StreamToFile(Stream stream, string fileName)
    {
        // 把 Stream 转换成 byte[] 
        byte[] bytes = new byte[stream.Length];
        stream.Read(bytes, 0, bytes.Length);
        // 设置当前流的位置为流的开始 
        stream.Seek(0, SeekOrigin.Begin);

        // 把 byte[] 写入文件 
        FileStream fs = new FileStream(fileName, FileMode.Create);
        BinaryWriter bw = new BinaryWriter(fs);
        bw.Write(bytes);
        bw.Close();
        fs.Close();
    }

    /// <summary> 
    /// 从文件读取 Stream 
    /// </summary> 
    public static Stream FileToStream(string fileName)
    {
        // 打开文件 
        FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read);
        // 读取文件的 byte[] 
        byte[] bytes = new byte[fileStream.Length];
        fileStream.Read(bytes, 0, bytes.Length);
        fileStream.Close();
        // 把 byte[] 转换成 Stream 
        Stream stream = new MemoryStream(bytes);
        return stream;
    }


}
